package com.bjfu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjfu.eduservice.entity.EduSubject;
import com.bjfu.eduservice.entity.excel.SubjectData;
import com.bjfu.eduservice.entity.subject.OneSubject;
import com.bjfu.eduservice.entity.subject.TwoSubject;
import com.bjfu.eduservice.listener.SubjectExcelListener;
import com.bjfu.eduservice.mapper.EduSubjectMapper;
import com.bjfu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjfu.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Guli
 * @since 2020-07-04
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(20001,"文件流错误");
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        // 查询全部一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneList = baseMapper.selectList(wrapperOne);

        // 查询全部二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoList = baseMapper.selectList(wrapperTwo);

        //创建最终返回集合
        List<OneSubject> finalList = new ArrayList<>();

        // 封装一级分类
        for (EduSubject one : oneList) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(one,oneSubject);

            // 封装二级分类
            List<TwoSubject> children = new ArrayList<>();
            for (EduSubject two : twoList) {
                TwoSubject twoSubject = new TwoSubject();
                BeanUtils.copyProperties(two,twoSubject);
                if(one.getId().equals(two.getParentId())){
                    children.add(twoSubject);
                }
            }

            oneSubject.setChildren(children);
            finalList.add(oneSubject);
        }

        return finalList;
    }
}
